<template>
  <div class="music-player">
    <div class="player-container">
      <!-- 左侧播放界面 -->
      <div class="player-left">
        <!-- 当前播放歌曲信息 -->
        <div class="current-song">
          <div class="song-cover" :style="{ backgroundImage: `url(${currentSong.cover})` }">
            <div class="cover-rotate" :class="{ playing: isPlaying }">
              <div class="cover-mask"></div>
            </div>
          </div>
          <div class="song-info">
            <h3 class="song-title">{{ currentSong.title }}</h3>
            <p class="song-artist">{{ currentSong.artist }}</p>
            <p class="song-username" @click="goToProfile">zhengbofu</p>
          </div>
        </div>

        <!-- 播放控制区 -->
        <div class="play-controls">
          <button class="btn-prev" @click="prevSong">&#9664;</button>
          <button class="btn-play" @click="togglePlay">{{ isPlaying ? '&#10074;&#10074;' : '&#9658;' }}</button>
          <button class="btn-next" @click="nextSong">&#9654;</button>
        </div>

        <!-- 进度条 -->
        <div class="progress-bar">
          <span class="current-time">{{ formatTime(currentTime) }}</span>
          <input 
            type="range" 
            class="progress-slider" 
            :value="currentTime" 
            :max="duration"
            @input="seek"
          >
          <span class="total-time">{{ formatTime(duration) }}</span>
        </div>

        <!-- 音量控制 -->
        <div class="volume-control">
          <button class="btn-volume" @click="toggleMute">
            {{ isMuted || volume === 0 ? '&#128263;' : '&#128266;' }}
          </button>
          <input 
            type="range" 
            class="volume-slider" 
            :value="isMuted ? 0 : volume" 
            max="1"
            step="0.01"
            @input="setVolume"
          >
        </div>
      </div>

      <!-- 右侧歌词区域 -->
        <div class="lyrics-container">
          <h3 class="lyrics-title">歌词</h3>
          <div class="lyrics-wrapper" ref="lyricsWrapper">
            <!-- 双排歌词容器 -->
            <div class="lyrics-double-column">
              <div 
                v-for="(line, index) in currentLyrics" 
                :key="index" 
                :class="['lyric-line', { 'active': currentLyricIndex === index }]"
              >
                {{ line.text }}
              </div>
            </div>
            <div v-if="!currentLyrics || currentLyrics.length === 0" class="no-lyrics">
              <p>暂无歌词</p>
            </div>
          </div>
        </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, onBeforeUnmount, watch, nextTick } from 'vue'
import { useMusicStore } from '../stores/music.js'
import { useRouter } from 'vue-router'

const store = useMusicStore()
const audioRef = ref(null)
const lyricsWrapper = ref(null)
const router = useRouter()

// 跳转到个人主页
const goToProfile = () => {
  router.push('/profile')
}

// 计算属性
const currentSong = computed(() => store.currentSong)
const isPlaying = computed(() => store.isPlaying)
const volume = computed(() => store.volume)
const isMuted = computed(() => store.isMuted)
const currentTime = computed(() => store.currentTime)
const duration = computed(() => store.duration)
const isVip = computed(() => store.isVip)

// 试听计时器
let previewTimer = null

// 提示信息
const showToast = (message, duration = 3000) => {
  // 创建toast元素
  const toast = document.createElement('div')
  toast.className = 'music-toast'
  toast.textContent = message
  document.body.appendChild(toast)
  
  // 显示toast
  setTimeout(() => {
    toast.style.opacity = '1'
  }, 10)
  
  // 隐藏并移除toast
  setTimeout(() => {
    toast.style.opacity = '0'
    setTimeout(() => {
      document.body.removeChild(toast)
    }, 300)
  }, duration)
}

// 歌词相关
const currentLyricIndex = ref(-1)
const currentLyrics = computed(() => {
  return currentSong.value?.lyrics || []
})

// 音频元素
let audioElement = null

// 音频错误处理
const handleAudioError = () => {
  if (isPlaying.value) {
    store.togglePlay()
    showToast('音频加载失败，请尝试其他歌曲')
  }
  console.error('音频加载错误:', audioElement.error)
}

// 初始化
onMounted(() => {
  audioElement = new Audio()
  audioRef.value = audioElement
  
  // 设置音频事件监听
  audioElement.addEventListener('timeupdate', handleTimeUpdate)
  audioElement.addEventListener('ended', handleEnded)
  audioElement.addEventListener('loadedmetadata', handleLoadedMetadata)
  audioElement.addEventListener('error', handleAudioError) // 添加错误处理
  
  // 监听歌曲切换事件
  window.addEventListener('songChanged', handleSongChanged)
})

// 清理
onUnmounted(() => {
  if (audioElement) {
    audioElement.removeEventListener('timeupdate', handleTimeUpdate)
    audioElement.removeEventListener('ended', handleEnded)
    audioElement.removeEventListener('loadedmetadata', handleLoadedMetadata)
    audioElement.removeEventListener('error', handleAudioError) // 移除错误处理监听
    audioElement.pause()
  }
  
  // 移除歌曲切换事件监听
  window.removeEventListener('songChanged', handleSongChanged)
  
  // 清理计时器
  if (previewTimer) {
    clearTimeout(previewTimer)
    previewTimer = null
  }
})

// 播放/暂停切换
const togglePlay = () => {
  if (isPlaying.value) {
    // 如果当前正在播放，清除试听计时器
    if (previewTimer) {
      clearTimeout(previewTimer)
      previewTimer = null
    }
    audioElement.pause()
  } else {
    audioElement.src = currentSong.value.url
    audioElement.play()
    
    // 检查是否是付费歌曲且用户不是会员
    if (currentSong.value.isPremium && !isVip.value) {
      // 显示试听提示
      showToast('非会员只能试听10秒，请开通会员收听完整歌曲')
      
      // 设置10秒后暂停播放
      if (previewTimer) {
        clearTimeout(previewTimer)
      }
      previewTimer = setTimeout(() => {
        if (audioElement && isPlaying.value) {
          audioElement.pause()
          store.togglePlay()
          showToast('试听已结束，开通会员收听完整歌曲')
        }
        previewTimer = null
      }, 10000)
    }
  }
  store.togglePlay()
}

// 上一首
const prevSong = () => {
  store.prevSong()
  currentLyricIndex.value = -1
  if (isPlaying.value) {
    audioElement.src = currentSong.value.url
    audioElement.play()
  }
}

// 下一首
const nextSong = () => {
  store.nextSong()
  currentLyricIndex.value = -1
  if (isPlaying.value) {
    audioElement.src = currentSong.value.url
    audioElement.play()
  }
}

// 调整进度
const seek = (event) => {
  const newTime = parseFloat(event.target.value)
  store.setCurrentTime(newTime)
  audioElement.currentTime = newTime
  updateLyrics()
}

// 设置音量
const setVolume = (event) => {
  const newVolume = parseFloat(event.target.value)
  store.setVolume(newVolume)
  audioElement.volume = newVolume
  if (newVolume > 0 && isMuted.value) {
    store.toggleMute()
    audioElement.muted = false
  }
}

// 静音切换
const toggleMute = () => {
  store.toggleMute()
  audioElement.muted = isMuted.value
}

// 格式化时间
const formatTime = (time) => {
  const minutes = Math.floor(time / 60)
  const seconds = Math.floor(time % 60)
  return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
}

// 音频事件处理函数
const handleTimeUpdate = () => {
  store.setCurrentTime(audioElement.currentTime)
  updateLyrics()
}

const handleEnded = () => {
  nextSong()
}

const handleLoadedMetadata = () => {
  store.setDuration(audioElement.duration)
}

// 处理歌曲切换事件
const handleSongChanged = () => {
  currentLyricIndex.value = -1
  if (isPlaying.value) {
    audioElement.src = currentSong.value.url
    audioElement.play()
  }
}

// 更新歌词显示
const updateLyrics = () => {
  if (!currentLyrics.value || currentLyrics.value.length === 0) {
    currentLyricIndex.value = -1
    return
  }

  // 找到当前应该显示的歌词索引
  const newIndex = currentLyrics.value.findIndex((line, index) => {
    const nextLine = currentLyrics.value[index + 1]
    if (!nextLine) return true
    return currentTime.value >= line.time && currentTime.value < nextLine.time
  })

  if (newIndex !== currentLyricIndex.value) {
    currentLyricIndex.value = newIndex
    // 滚动到当前歌词
    scrollToCurrentLyric()
  }
}

// 滚动到当前歌词
const scrollToCurrentLyric = async () => {
  await nextTick()
  if (lyricsWrapper.value && currentLyricIndex.value >= 0) {
    const activeLine = lyricsWrapper.value.querySelector('.lyric-line.active')
    if (activeLine) {
      const wrapperRect = lyricsWrapper.value.getBoundingClientRect()
      const lineRect = activeLine.getBoundingClientRect()
      const scrollTop = lyricsWrapper.value.scrollTop + 
                      lineRect.top - wrapperRect.top - 
                      wrapperRect.height / 2 + lineRect.height / 2
      lyricsWrapper.value.scrollTo({ top: scrollTop, behavior: 'smooth' })
    }
  }
}

// 监听currentSong变化，重置歌词索引
watch(currentSong, () => {
  currentLyricIndex.value = -1
  
  // 清除之前的试听计时器
  if (previewTimer) {
    clearTimeout(previewTimer)
    previewTimer = null
  }
})

// 清理函数中添加计时器清理
onBeforeUnmount(() => {
  if (previewTimer) {
    clearTimeout(previewTimer)
    previewTimer = null
  }
})</script>

<style scoped>
.music-player {
  background: #f8f9fa;
  color: #333;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  max-width: 1000px;
  margin: 0 auto;
  min-height: 350px;
}

.player-container {
  display: flex;
  gap: 30px;
  height: 100%;
  min-height: 310px;
}

/* 左侧播放界面 */
.player-left {
  flex: 1;
  min-width: 250px;
  display: flex;
  flex-direction: column;
}

.current-song {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  gap: 15px;
}

.song-cover {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background-size: cover;
  background-position: center;
  position: relative;
  overflow: hidden;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.cover-rotate {
  width: 100%;
  height: 100%;
  transition: transform 0.3s ease;
  position: relative;
}

.cover-rotate.playing {
  animation: rotate 20s linear infinite;
}

.cover-mask {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 20px;
  height: 20px;
  background: rgba(255, 255, 255, 0.6);
  border-radius: 50%;
}

.song-info {
  flex: 1;
}

.song-title {
  font-size: 20px;
  margin: 0 0 6px 0;
  font-weight: 500;
  color: #333;
}

.song-artist {
  font-size: 14px;
  color: #666;
  margin: 0 0 5px 0;
}

.song-username {
  font-size: 12px;
  color: #42b983;
  margin: 0;
  cursor: pointer;
  text-decoration: underline;
}

.song-username:hover {
  color: #35495e;
}

.play-controls {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 25px;
  margin-bottom: 20px;
}

.play-controls button {
  background: none;
  border: none;
  color: #666;
  cursor: pointer;
  font-size: 22px;
  transition: transform 0.2s ease, color 0.2s ease;
}

.play-controls button:hover {
  transform: scale(1.05);
  color: #333;
}

.btn-play {
  font-size: 32px !important;
  background: #e0e0e0;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  color: #333;
}

.btn-play:hover {
  background: #d0d0d0;
}

.progress-bar {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 15px;
}

.progress-slider {
  flex: 1;
  height: 4px;
  border-radius: 2px;
  background: #e0e0e0;
  outline: none;
  -webkit-appearance: none;
  cursor: pointer;
}

.progress-slider::-webkit-slider-thumb {
  -webkit-appearance: none;
  width: 14px;
  height: 14px;
  border-radius: 50%;
  background: #999;
  cursor: pointer;
  transition: transform 0.2s ease;
}

.progress-slider::-webkit-slider-thumb:hover {
  transform: scale(1.1);
  background: #666;
}

.current-time, .total-time {
  font-size: 12px;
  color: #888;
  min-width: 40px;
  text-align: center;
}

.volume-control {
  display: flex;
  align-items: center;
  gap: 8px;
}

.btn-volume {
  background: none;
  border: none;
  color: #666;
  cursor: pointer;
  font-size: 16px;
  transition: color 0.2s ease;
}

.btn-volume:hover {
  color: #333;
}

.volume-slider {
  width: 80px;
  height: 3px;
  border-radius: 1.5px;
  background: #e0e0e0;
  outline: none;
  -webkit-appearance: none;
  cursor: pointer;
}

.volume-slider::-webkit-slider-thumb {
  -webkit-appearance: none;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background: #999;
  cursor: pointer;
}

/* 右侧歌词区域 */
.lyrics-container {
  flex: 1;
  min-width: 250px;
  background: #fff;
  border-radius: 8px;
  padding: 15px;
  display: flex;
  flex-direction: column;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  height: 100%;
}

.lyrics-title {
  margin: 0 0 12px 0;
  font-size: 1.1rem;
  text-align: center;
  color: #333;
  font-weight: 500;
}

.lyrics-wrapper {
  flex: 1;
  overflow-y: auto;
  padding: 10px 0;
  display: flex;
  flex-direction: column;
  gap: 8px;
  position: relative;
  text-align: center;
}

/* 歌词滚动优化 */
.lyrics-wrapper {
  scroll-behavior: smooth;
}

.lyrics-wrapper::-webkit-scrollbar {
  width: 3px;
}

.lyrics-wrapper::-webkit-scrollbar-track {
  background: transparent;
}

.lyrics-wrapper::-webkit-scrollbar-thumb {
  background: #ddd;
  border-radius: 2px;
}

.lyrics-wrapper::-webkit-scrollbar-thumb:hover {
  background: #ccc;
}

/* 双列歌词容器 */
.lyrics-double-column {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px 20px;
  align-items: center;
  padding: 0 10px;
}

/* 歌词显示优化 */
.lyric-line {
  text-align: center;
  font-size: 0.9rem;
  padding: 4px 0;
  color: #666;
  transition: all 0.3s ease;
  line-height: 1.4;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 100%;
}

.lyric-line.active {
  color: #333;
  font-size: 0.95rem;
  font-weight: 500;
  transform: none;
  opacity: 1;
}

/* 调整当前歌词在双列布局中的显示 */
.lyrics-double-column .lyric-line.active {
  grid-column: 1 / -1;
  font-size: 1rem;
  padding: 6px 0;
  margin: 5px 0;
}

/* 歌词上下行渐变效果 */
.lyrics-wrapper::before,
.lyrics-wrapper::after {
  content: '';
  position: absolute;
  left: 0;
  right: 0;
  height: 40px;
  pointer-events: none;
}

.lyrics-wrapper::before {
  top: 0;
  background: linear-gradient(to bottom, #fff 0%, rgba(255,255,255,0) 100%);
}

.lyrics-wrapper::after {
  bottom: 0;
  background: linear-gradient(to top, #fff 0%, rgba(255,255,255,0) 100%);
}

.no-lyrics {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0.6;
  color: #999;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* Toast样式 */
.music-toast {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 12px 24px;
  border-radius: 6px;
  font-size: 14px;
  z-index: 9999;
  opacity: 0;
  transition: opacity 0.3s ease;
  pointer-events: none;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .player-container {
    flex-direction: column;
  }
  
  .song-cover {
    width: 90px;
    height: 90px;
  }
  
  .play-controls {
    gap: 20px;
  }
}
</style>